package com.jrx.anytxn.investor.timer.config;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * 参数库数据源配置类
 *
 */
@Configuration
@EnableConfigurationProperties(ParamHikariDataConfig.class)
@MapperScan(basePackages = {"com.jrx.anytxn.param.mapper"}, sqlSessionTemplateRef = "paramSqlSessionTemplate")
public class ParamDataSourceConfig {
    private static final String CONFIG_LOCATION = "classpath:/mybatis/mybatis-config.xml";
    private static final String MAPPER_LOCATION = "classpath*:/mybatis/mapping/*/*.xml";
    @Bean(name = "paramDataSource")
    public DataSource dataSource(ParamHikariDataConfig paramHikariDataConfig) {
        return new HikariDataSource(paramHikariDataConfig);
    }

    @Bean(name = "paramSqlSessionFactory")
    public SqlSessionFactory paramSqlSessionFactory(@Qualifier("paramDataSource") DataSource dataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        sessionFactory.setConfigLocation(new PathMatchingResourcePatternResolver().getResource(CONFIG_LOCATION));
        return sessionFactory.getObject();
    }

    @Bean(name = "paramTransactionManager")
    public PlatformTransactionManager paramTransactionManager(@Qualifier("paramDataSource") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "paramSqlSessionTemplate")
    public SqlSessionTemplate paramSqlSessionTemplate(@Qualifier("paramSqlSessionFactory")SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory, ExecutorType.BATCH);
    }
}